package com.example.victory.utils;


import com.example.victory.exception.GlobalError;
import com.example.victory.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class BigDataApiAuthUtil {
    @Value("${app.secureId:drT8H36sipYsprDBSvEL84tnkqBfxwhozr7b}")
    private String appSecureId;
    @Value("${app.secureKey:YsqVwKNxbC2krRBtAI8kv6GCpjximlFs}")
    private String appSecureKey;
    @Autowired
    private RedisService redisService;

    private  static  String bigData="inner-business-crmapi:app:big:data:access";

    public String getAccessAuthHeader(){
        String access=null;
        try {
            access= (String) redisService.getRedisTemplate().opsForValue().get(bigData);
            if(!StringUtils.isEmpty(access)) return access;
            access=getAccessAuthHeader(appSecureId,appSecureKey);
            redisService.getRedisTemplate().opsForValue().set(bigData,access,8, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error(String.format("获取大数据的鉴权异常或者redis异常,e=%s",e));
            //throw new GlobalException(ServiceError.REQUEST_BIGDATA_ERROR);
            access=getAccessAuthHeader(appSecureId,appSecureKey);
        }
        return  access;
    }


    private static String generateSignature(String publicKey, long timestamp, int randomValue, String privateKey)
            throws UnsupportedEncodingException {
        Base64 base64 = new Base64();
        byte[] baseStr = base64
                .encode(new HmacUtils(HmacAlgorithms.HMAC_SHA_256, privateKey).hmac(publicKey + timestamp + randomValue));
        String signature = URLEncoder.encode(new String(baseStr), "UTF-8");
        return signature;
    }
    private static String getAccessAuthHeader(String secureId, String secureKey)  {
        Long timestamp = System.currentTimeMillis();
        Integer nonce = new Random().nextInt(10 * 8) + 1;

        String signature = null;
        try {
            signature = generateSignature(secureId, timestamp, nonce, secureKey);
        } catch (UnsupportedEncodingException e) {
            throw new GlobalException(GlobalError.REQUEST_BIGDATA_SIGN_ERROR);
        }
        String accessHeader = "SDP " + secureId + " " + timestamp + " " + nonce + " " + signature;
        // System.out.println("access encode=" + accessHeader);
        return accessHeader;
    }
    public static void main(String[] args) throws UnsupportedEncodingException {
        String secureId = "drT8H36sipYsprDBSvEL84tnkqBfxwhozr7b";
        String secureKey = "YsqVwKNxbC2krRBtAI8kv6GCpjximlFs";
        System.out.println(getAccessAuthHeader(secureId, secureKey));
    }
}